<template>
  <view :style="bodyStyle">
    <swiper v-if="compList.length > 1" style="height: 380rpx">
      <swiper-item v-for="(itemList, itemIndex) in compList" :key="itemIndex">
        <view class="grid">
          <view
            v-for="(item, index) in itemList"
            :key="index"
            class="item"
            :style="{ width: `calc(100% / ${columns})` }"
            @click="emit('click', item)"
          >
            <image mode="widthFix" :src="item[imgField]" />
            <view class="title">{{ item[titleField] }}</view>
          </view>
        </view>
      </swiper-item>
    </swiper>
    <view v-else class="grid">
      <view
        v-for="(item, index) in compList[0]"
        :key="index"
        class="item"
        :style="{ width: `calc(100% / ${columns})` }"
        @click="emit('click', item)"
      >
        <image mode="widthFix" :src="item[imgField]" />
        <view class="title">{{ item[titleField] }}</view>
      </view>
    </view>
  </view>
</template>
<script lang="ts" setup>
import { computed, StyleValue } from "vue";

interface Props {
  /**列数 */
  columns?: number;
  /**宫格数据 */
  list: Record<string, any>[];
  /**图片地址字段 */
  imgField?: string;
  /**标题字段 */
  titleField?: string;
  /**样式 */
  bodyStyle?: StyleValue;
}
const props = withDefaults(defineProps<Props>(), {
  columns: 4,
  imgField: "image",
  titleField: "title",
});
const emit = defineEmits(["click"]);
const compList = computed(() => {
  if (props.list.length <= 8) {
    return [props.list];
  } else {
    const arr = [];
    for (let i = 0; i < props.list.length; i += 8) {
      arr.push(props.list.slice(i, i + 8));
    }
    return arr;
  }
});
</script>
<style scoped>
.grid {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
.grid .item {
  margin: 8rpx 0;
}
.grid .item image {
  display: block;
  width: 60%;
  margin: auto;
  border-radius: 16rpx;
}
.grid .item .title {
  margin: 16rpx auto;
  text-align: center;
}
</style>
